package controller

import (

	"linker/module"
	"github.com/kataras/iris"
	"github.com/yuin/gopher-lua"
	"encoding/json"
	"fmt"
)

type LinkController struct {
	Ctx iris.Context
	MysqlLink module.MysqlLink
}

func (c *LinkController) GetLinkBy(name string)  {

	params:=c.Ctx.Request().URL.Query()
	p,_:=json.Marshal(params)
	c.Ctx.JSON(c.runScript(name,string(p)))
}

func(c *LinkController) runScript(name string,param string) interface{}{
	L := lua.NewState()
	defer L.Close()

	L.PreloadModule("mysql", c.MysqlLink.Loader)

	if err := L.DoFile("./script/"+name+".lua"); err != nil {
		fmt.Println(err)
		return map[string]interface{}{
			"errmsg":"not found",
		}
	}
	err:=L.CallByParam(lua.P{
		Fn:L.GetGlobal("run"),
		NRet:1,
		Protect:true,
	},lua.LString(param))

	if err!=nil{
		panic(err)
	}
	ret:=L.Get(-1)
	L.Pop(1)
	res:=make(map[string]interface{},0)
	json.Unmarshal([]byte(ret.(lua.LString)),&res)

	return res
}